package com.candoo.oil.scan;


import android.accounts.NetworkErrorException;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

/**
 * Created by Tinder on 2016/8/23.
 */
public class httpClientClass {


    public static P_Response_Login Login(String Account,String SessionId) {
        P_Response_Login r = new P_Response_Login();
        try {

            JSONObject d = new JSONObject();//"{'id':112233}"
            d.put("cmd", 1001);
            d.put("account", Account);
            d.put("sessionid", SessionId);
            JSONObject rr = httpClientClass.PostJson(Config.Url, d);
            r.flag = rr.getInt("code");
            r.msg = rr.getString("msg");

        } catch (Exception e) {
            r.flag = -404;
            r.msg = e.toString();
        } finally {

        }
        return r;
    }
    public static P_Response_Read Read(String Id) {
        P_Response_Read r = new P_Response_Read();
        try {

            JSONObject d = new JSONObject();//"{'id':112233}"
            d.put("cmd", 1002);
            d.put("oId", Id);
            JSONObject rr = httpClientClass.PostJson(Config.Url+"/read", d);
            r.flag = rr.getInt("code");
            r.msg = rr.getString("msg");



            if(r.flag==0)
            {
                JSONObject rrr=rr.getJSONObject("Data");

                r.oId=rrr.getString("oId");
                r.Type=rrr.getString("oType");
                r.Warehouse=rrr.getString("oWarehouse");
                r.Supplier=rrr.getString("oSupplier");


                JSONArray ja=rrr.getJSONArray("List");

                for(int i=0;i<ja.length();i++){
                    JSONObject dd=ja.getJSONObject(i);
                   P_Item item=new P_Item();
                    item.Id=dd.getString("id");
                    item.Name=dd.getString("name");
                    item.Count=dd.getInt("count");
                    item.Model=dd.getString("model");
                    r.list.add(item);
                }
            }
            else
            {
                r.flag=r.flag*-1;
                r.msg=rr.getString("desc");
            }

        } catch (Exception e) {
            r.flag = -404;
            r.msg = e.toString();
        } finally {

        }
        return r;
    }

    public static P_Response_Save Save(String Id, ArrayList<P_Item> list) {
        P_Response_Save r = new P_Response_Save();
        try {

            JSONObject d = new JSONObject();//"{'id':112233}"
            d.put("cmd", 1003);
            d.put("oId", Id);
            JSONArray ja=new JSONArray();
            for(int i=0;i<list.size();i++)
            {
                P_Item item=list.get(i);
                JSONObject dd = new JSONObject();//"{'id':112233}"
                dd.put("id", item.Id);
                JSONArray ja2=new JSONArray();
                for(int j=0;j<item.List.length;j++)
                {
                    ja2.put(item.List[j]);
                }
                dd.put("list", ja2);
                ja.put(dd);
            }
            d.put("List",ja);
            JSONObject rr = httpClientClass.PostJson(Config.Url+"/save", d);
            r.flag = rr.getInt("code");
            r.msg = rr.getString("msg");

            if(r.flag!=0)
            {
                r.flag=r.flag*-1;
                r.msg=rr.getString("desc");
            }

        } catch (Exception e) {
            r.flag = -404;
            r.msg = e.toString();
        } finally {

        }
        return r;
    }



private  static String _cookie="";
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

    private static String getStringFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 模板代码 必须熟练
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        is.close();
        String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
        os.close();
        return state;
    }

    public  static  JSONObject PostJson(String url,JSONObject d) {
        String r = PostString(url, d.toString());

        try {
            JSONObject rr= new JSONObject(r);
            return rr;
        }
        catch (Exception e)
        {}
        finally {

        }
        return null;
    }
    /*
    * public static String post(String url, String content) {
        HttpURLConnection conn = null;
        try {
            // 创建一个URL对象
            URL mURL = new URL(url);
            // 调用URL的openConnection()方法,获取HttpURLConnection对象
            conn = (HttpURLConnection) mURL.openConnection();

            conn.setRequestMethod("POST");// 设置请求方法为post
            conn.setReadTimeout(5000);// 设置读取超时为5秒
            conn.setConnectTimeout(10000);// 设置连接网络超时为10秒
            conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容

            // post请求的参数
            String data = content;
            // 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
            OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
            out.write(data.getBytes());
            out.flush();
            out.close();

            int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
            if (responseCode == 200) {
                InputStream is = conn.getInputStream();
                String response = getStringFromInputStream(is);
                return response;
            } else {
                throw new NetworkErrorException("response status is "+responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();// 关闭连接
            }
        }

        return null;
    }

    * */

    public static String PostString(String url,String d)
    {
        Log.e("url",url);
        Log.e("==>",d);
        //JSONObject jsonObject = new JSONObject();
        //InputStream inputStream = null;
        HttpURLConnection conn = null;

        try{
            URL _url = new URL(url);
            conn = (HttpURLConnection) _url.openConnection();

        /* optional request header */
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Connection", "keep-alive");//
        /* optional request header */
            conn.setRequestProperty("Accept", "application/json");
           // dto.setCreator(java.net.URLEncoder.encode(dto.getCreator(), "utf-8"));
           // urlConnection.setRequestProperty("Cookie", _cookie);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);

           // urlConnection.setDoOutput(true);
            conn.setConnectTimeout(10000);// 设置连接网络超时为10秒
            conn.setReadTimeout(5000);// 设置读取超时为5秒
            conn.setDoOutput(true);
            conn.setDoInput(true);
           // conn.connect();
          //  OutputStream wr = conn.getOutputStream();
           // wr.write(d.getBytes());
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(d);
            wr.flush();
            wr.close();

            int responseCode = conn.getResponseCode();
            Log.e("statusCode","code:"+responseCode);
           // if (statusCode == 200 ) {
               // _cookie = conn.getHeaderField("set-cookie");
             //   inputStream = new BufferedInputStream(conn.getInputStream());
             //   String response = convertInputStreamToString(inputStream);
             //   Log.e("<==",response);
             //   return response;
           // }
            if (responseCode == 200) {
                InputStream is = conn.getInputStream();
                String response = getStringFromInputStream(is);
                Log.e("<==",response);
                return response;
            } else {
              //  conn.
                throw new NetworkErrorException("response status is "+responseCode);
            }
        }
        catch (Exception e){

            Log.e("httpex",e.toString());
            e.printStackTrace();
        }
        finally {
           // if (inputStream != null) {
            //    try {
           //         inputStream.close();
            //    } catch (IOException e) {
             //       e.printStackTrace();
             //   }
          //  }
            if (conn != null) {
                conn.disconnect();
            }
        }

        return null;

    }

}
